const express = require('express');
const moment = require('moment')
const db = require('../core/DBhelper');
const fs = require('../core/FileHelp');
// 创建路由
const apiRouters = express.Router();

// post登陆
apiRouters.post('/login', async (request, response, next) => {
    const userObj = request.body;
    let sqlLogin = "SELECT `u_id`,`u_name`,`u_sex`,`u_address`,`u_email`,`u_nickname`,`u_phone`,`u_create` FROM `userinfo` WHERE `u_name` = ? AND `u_pwd`=? AND `u_staus`='1';"
    let params = [
        userObj.name,
        userObj.pwd
    ]
    try {
        let res = await db.exec(sqlLogin, params);
        const result = { msg: '登陆失败', code: 200 }
        if (res && res.length >= 1) {
            result['msg'] = '登陆成功';
            res[0].u_create = moment(res[0].u_create).format('YYYY-MM-DD hh:mm:ss')
            result['data'] = res[0]
        }
        setTimeout(() => {
            response.json(result)
        }, 1000)
    } catch (error) {
        response.json({
            msg: '登录失败',
            code: -200,
            error
        })
    }
})
// post注册
apiRouters.post('/reg', async (request, response, next) => {
    let userObj = request.body;
    let sqlReg = "INSERT INTO `userinfo`(`u_name`,`u_pwd`,`u_sex`,`u_address`,`u_email`,`u_nickname`,`u_phone`,`u_create`)VALUES(?,?,?,?,?,?,?,?);"
    let parsms = [
        userObj.name,
        userObj.pwd,
        userObj.sex,
        userObj.address,
        userObj.email,
        userObj.nickname,
        userObj.phone,
        moment(Date.now()).format('YYYY-MM-DD hh:mm:ss')
    ]

    try {
        let res = await db.exec(sqlReg, parsms);
        let isReg = (res && res.affectedRows >= 1);
        let result = {
            msg: isReg ? '注册成功' : '注册失败',
            code: 200
        }
        response.json(result)
    } catch (error) {
        let result = {
            msg: '注册失败',
            code: -200,
            error
        }
        response.json(result)
    }
})
// get 检查用户名
apiRouters.get('/checkName', async (request, response, next) => {
    let { name } = request.query;

    let sql = "SELECT *FROM `userinfo` WHERE `u_staus`=1 AND u_name=?;";
    let result = await db.exec(sql, [name]);
    let res = !(result && result.length >= 1);
    response.send(res)
})
apiRouters.get("/getByPid", async (request, response, next) => {
    // apiRoutes里的代码都会在 app.js里运行
    let { pId } = request.query;
    let res = await file.getFile("./data/list_production.json");
    let list = JSON.parse(res || '[]')
    var goodsObj = list.find((el, index) => {
        return el.pid == pId
    })

    response.json(goodsObj);
})
// 获取产品列表
apiRouters.get('/getList', async (request, response, next) => {
    let res = await fs.getFile('./data/list_production.json')
    response.send(res)
})
// 加入购物车
apiRouters.post('/addCart', async (request, response, next) => {
    let { u_id, pprice, pname, pid, num, index_img } = request.body;
    console.log(request.body);
    let sqlQuery = "SELECT * FROM `cart`  WHERE `c_status`=1 AND `p_id`=? AND `u_id`=?";
    let paramsQuery = [pid, u_id];
    try {
        let queryResult = await db.exec(sqlQuery, paramsQuery)
        let isAdd = (queryResult && queryResult.length >= 1);//已购买
        if (isAdd) {//已购买,修改数量和总金额
            let sqlUpdate = "UPDATE cart SET`p_number`=p_number+? ,`p_total`=p_number*`p_price` WHERE `c_status`=1 AND `p_id`=? AND `u_id`=?";
            let paramsUpdate = [num, pid, u_id];
            let updateResult = await db.exec(sqlUpdate, paramsUpdate);
            let updateIsSuccess = (updateResult && updateResult.affectedRows >= 1)
            if (updateIsSuccess) {
                response.json({ msg: "加入购物车成功", flag: "update", code: 200 })
            } else {
                response.json({ msg: "加入购物车失败", flag: "update", code: 200 })
            }
        } else {//从来没购买过,插入1条新的数据

            let sqlInert = "INSERT INTO `cart` (`p_id`,`p_name`,`p_price`,`p_number`,`p_total`,`p_create`,`p_img`,`u_id`)VALUE(?,?,?,?,?,?,?,?)";
            let paramsInert = [
                pid,
                pname,
                pprice,
                num,
                pprice * num,
                moment(Date.now()).format("YYYY-MM-DD hh:mm:ss"),
                index_img,
                u_id
            ]

            let inserResult = await db.exec(sqlInert, paramsInert);

            let inserIsSuccess = (inserResult && inserResult.affectedRows >= 1)

            response.json({ msg: inserIsSuccess ? "加入购物车成功" : "加入购物车失败", flag: "insert", code: 200 })

        }
    } catch (error) {
        response.json({ msg: "加入购物车失败", error, code: -200 })
    }
})
module.exports = {
    apiRouters
}